package com.xianxing.service.user.controller;

import com.xianxing.common.pojo.AuthToken;
import com.xianxing.common.util.MessageConstant;
import com.xianxing.common.util.Response;
import com.xianxing.service.user.pojo.User;
import com.xianxing.service.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Value("${clientId}")
    private String client;
    @Value("${clientSecret}")
    private String clientSecret;

    @PostMapping("/login")
    public Response login(@RequestBody Map map, HttpServletResponse response){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new RuntimeException("请输入用户名或密码");
        }
        //申请令牌
        AuthToken authoToken = userService.login(username, password, client, clientSecret);
        //存入cookie返回
        this.storeToCookie(authoToken,response);
        //返回结果
        return Response.OK("用户认证成功",authoToken);
    }

    @GetMapping("/username/{username}")
    public Response findUserByUsername(@PathVariable String username){

        User user = userService.findUserByUsername(username);
        if(!StringUtils.isEmpty(user)){
            return Response.OK(MessageConstant.QUERY_USER_SUCCESS,user);
        }
        return Response.FAIL(MessageConstant.QUERY_USER_FAIL);
    }

    //将jti存入cookie返回
    private void storeToCookie(AuthToken authoToken, HttpServletResponse response) {
        Cookie cookie = new Cookie("jti",authoToken.getJti());
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(authoToken.getExpires_in().intValue());
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
    }
}
